﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace MulticastTestReceiver
{
    class Program
    {
        //static void Main(string[] args)
        //{
        //    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
        //    ProtocolType.Udp);
        //    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9988);
        //    s.Bind(ipep);
        //    IPAddress ip = IPAddress.Parse("224.5.6.7");

        //    s.SetSocketOption(SocketOptionLevel.IP,
        //        SocketOptionName.AddMembership,
        //            new MulticastOption(ip, IPAddress.Any));
        //    while (true)
        //    {
        //        byte[] b = new byte[1024];
        //        s.Receive(b);
        //        string str = System.Text.Encoding.ASCII.GetString(b, 0, b.Length);
        //        Console.WriteLine(str.Trim());
        //    }
        //}

        static void Main(string[] args)
        {
            UdpClient listener = new AdvUdpClient(9988);
            IPAddress CurrentIpAddress = IPAddress.Parse("224.5.6.7");
            listener.JoinMulticastGroup(CurrentIpAddress, 5);

            while (true)
            {
                IPEndPoint caller = null;
                byte[] received = listener.Receive(ref caller);
                string str = System.Text.Encoding.ASCII.GetString(received, 0, received.Length);
                Console.WriteLine("Caller={0}; Message={1}", caller.Address, str.Trim()); 
            }
        }
    }

    class AdvUdpClient : UdpClient
    {
        public AdvUdpClient(int port)
        {
            this.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            this.Client.Bind(new IPEndPoint(IPAddress.Any, port));
        }
    }
}
